import router from './router';
import { useMenuStore } from './store/menuStore';
import { loadVueFile } from './utils';
import { listToRoutes } from '@/utils/router';
import { brsFetch } from './utils/request';
import { useSystemStore } from './store/systemStore';
import { ISystem } from './types/ISystem';

router.beforeEach(async (to, form, next) => {
	const menuStore = useMenuStore();
	if (!menuStore.menus.length) {
		try {
			const res = await brsFetch<ISystem.IMenu[]>({ url: '/mock/menu' });
			const routes = listToRoutes(res.data, '0');
			router.addRoute({
				path: '/',
				component: loadVueFile('../layouts/index.vue'),
				children: routes,
			});
			router.addRoute({
				path: '/',
				component: loadVueFile('../layouts/index.vue'),
				children: [
					{
						path: '/404',
						name: '404',
						component: () => import('@/layouts/404.vue'),
					},
				],
			});
			router.addRoute({
				path: '/:path(.*)',
				redirect: '/404',
			});
			menuStore.setMenus(res.data);
			next({
				path: to.path,
				replace: true,
			});
		} catch (error) {
			next({
				path: '/',
				replace: true,
			});
		}
	} else {
		if (to.meta.menu) {
			const menu = to.meta.menu as ISystem.IMenu;
			menuStore.addTabs(menu);
			const systemStore = useSystemStore();
			document.title = `${systemStore.title} - ${menu.name}`;
		}
		next();
	}
});
